from skimage import io
import pandas as pd
import cv2 as cv
import os
import numpy as np
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import pickle
i = 0
l_list = []
for f in os.listdir("E:/renlianshibie"):
    if('.py' in f):
        continue
    # print(f)
    img_list = []
    for j in os.listdir("E:/renlianshibie/"+f):
        if '.py' in j:
            continue
        img = cv.imread("E:/renlianshibie/"+f+"/"+j, 0)
        # 1. 创建级联分类器
        face_cascade = cv.CascadeClassifier()
        # 2. 引入训练好的可用于人脸识别的级联分类器模型
        face_cascade.load("E:/haarcascade_frontalface_alt.xml")
        # 3. 用此级联分类器识别图像中的所有人脸信息，返回一个包含有所有识别的人联系系的列表
        # 列表中每一个元素包含四个值：面部左上角的坐标(x,y) 以及面部的宽和高(w,h)
        faces = face_cascade.detectMultiScale(img)
        faces_list = len(list(faces))
        # 4. 为图像中的所有面部画框
        if faces_list != 0:
            for (x, y, w, h) in faces:
                cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
            img_faces = img[y:y+h, x:x+w]
        if faces_list == 0:
            continue
        if(img_faces.shape[0] < 32):
            continue
        if(img_faces.shape[0] >= 32):
            img = cv.resize(img_faces, (32, 32))
            img = img.ravel()
            img_list.append(img)
    df = pd.DataFrame(img_list)
    df.insert(df.shape[1], 'label', i)
    l_list.append(df.values)
    i = i+1
df_array = np.zeros(1025, dtype=int)
l = 0
a_list = []
d = l_list[0]
for k in range(1, len(l_list)):
    d1 = l_list[k]
    d = np.concatenate((np.array(d), np.array(d1)), axis=0)
df = pd.DataFrame(d)
X = df.drop([1024], axis=1)
y = df[1024]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
acc = clf.score(X_test,y_test)
with open("acc",'wb') as j:
    pickle.dump(acc,j)
    print("已经保存准确率")
with open("clf1", 'wb') as f:
    pickle.dump(clf, f)
    print("已保存clf")
